package middleware

import (
	"fmt"
	"github.com/kataras/iris/v12"
	"wit-admin-go/conf"
	"wit-admin-go/system/app/controller"
	"wit-admin-go/system/app/dto"
	witJwt "wit-admin-go/system/jwt"
	"wit-admin-go/system/router"
	"wit-admin-go/system/utils"
	log "wit-admin-go/system/zaplogger"
)

// CheckAuthorization 登录验证中间件
func CheckAuthorization(ctx iris.Context, F *dto.Log) {
	//log.Info("登录验证中间件:" + ctx.Path())
	// 放行设置
	swaggerUrl := []string{"/wit/index.html", "/wit/swagger-ui-bundle.js", "/wit/swagger-ui-standalone-preset.js", "/wit/wit-api.json", "/wit/wit-doc.json", "/wit/favicon-16x16.png", "/wit/favicon-32x32.png", "/wit/swagger-ui.css", "/wit/swagger-ui-standalone-preset.js.map", "/wit/swagger-ui-bundle.js.map", "/wit/swagger-ui.css.map"}
	urlItem := append(swaggerUrl, router.PublicUrl...)
	fmt.Println(urlItem)
	if utils.IsStringInArray(ctx.Path(), urlItem) != nil {
		// 从请求头中获取Token
		token := ctx.GetHeader(conf.CONFIG.WitAdmin.Token)
		if utils.IsEmpty(token) {
			token = ctx.GetHeader("token")
			if utils.IsEmpty(token) {
				token = ctx.GetCookie(conf.CONFIG.WitAdmin.Token)
			}
		}
		// 请求头 Authorization或token 为空
		if utils.IsEmpty(token) {
			_ = ctx.JSON(dto.NewResult("", 401, "登录验证失败，请重新登录！"))
			// 打印消息
			log.Log.Warn("登录验证失败，请重新登录！")
			ctx.StopExecution()
			return
		}
		// 验证token
		vToken, err := witJwt.ParseToken(token)
		if err != nil {
			log.Log.Warn("token 解析异常信息：", err)
			_ = ctx.JSON(dto.NewResult("", 401, "登录验证失败，请重新登录！"))
			// 打印消息
			log.Log.Warn("登录验证失败，请重新登录！")
			ctx.StopExecution()
			return
		}
		// 验证权限, WebSocket地址不验证接口权限
		if ctx.Path() != conf.CONFIG.WitAdmin.WebSocketPath {
			utils.CasbinServe(ctx, vToken)
			F.CreateId = vToken.Id
		}
	}
	var sysLog controller.LogController
	//向数据库添加请求日志
	sysLog.CreateLogSys(F)
	ctx.Next()
}
